﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;

namespace mvvm4
{
    public class ViewModel : INotifyPropertyChanged
    {
        private DataModel _model;

        public ViewModel()
        {
            SelectedItem = new DataModel();
            Persons = new ObservableCollection<DataModel>();

            // Can Execute muss man nicht angeben, ist aber sicher interessant für die anderen...
            AddDataCommand = new RelayCommand(_ => UpdateList(), _ => ButtonActivated());
        }

        public ICommand AddDataCommand { get; private set; }


        public ObservableCollection<DataModel> Persons { get; private set; }

        public DataModel SelectedItem
        {
            get { return _model; }
            set
            {
                if (value != _model)
                {
                    _model = value;
                    InvokePropertyChanged("SelectedItem");
                }
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        public void UpdateList()
        {
            Persons.Add(_model);
            SelectedItem = new DataModel();
        }

        private bool ButtonActivated()
        {
            return !string.IsNullOrEmpty(SelectedItem.Name) && !string.IsNullOrEmpty(SelectedItem.Address);
        }

        private void InvokePropertyChanged(string propertyName)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            PropertyChangedEventHandler changed = PropertyChanged;
            if (changed != null) changed(this, e);
        }
    }
}